import React, { useEffect, useState } from "react";
import { Modal, Table, Form, Radio, Input, Space, Button } from "antd";
import { modalPropsType } from "@/constants/types";
import { fetchStaffsList } from "../../services";
import { yesOrNo } from "@/constants/dictData";

const { Item } = Form;
const rules = [{required: true, message: '此项必填'}];

const CompanyPhoneManage = ({title, visible, onCancel, onSubmit, currentRow}: modalPropsType) => {
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState<any []>([]);
  const [copyData, setCopyData] = useState<any []>([]);


  const fetchPhoneList = async (id: string) => {
    const res = await fetchStaffsList({id});
    if (res?.code === '0') {
      const data = res?.data?.map((v: any) => ({...v, rowKey: v?.id}));
      setDataSource([...data]);
      setCopyData([...data]);
      form.setFieldsValue(data.reduce((p, v) => ({
        ...p,
        [v?.rowKey]: {...v}
      }), {}));
    }
  }

  const handleSubmit = async () => {
    const res = await form.validateFields();
    console.log("res", res);
    const submitValues = {
      customerId: currentRow?.id,
      staffsList: dataSource?.map(v => {
        return {
          ...res?.[v?.rowKey],
          id: v?.id
        }
      }),
      deletedIds: copyData?.filter(v => !v?.isAdd && dataSource?.every(s => s.id !== v?.id))?.map(v => v.id)
    }
    onSubmit(submitValues);
  }

  const handleDel = (record: any, index: number) => {
    const arr = [...dataSource];
    arr.splice(index, 1);
    setDataSource(arr);
    form.setFieldValue(record?.id, undefined);
  }

  const handleAdd = (index: number) => {
    const id = String(new Date().getTime() + Math.floor(Math.random() * 1000));
    const addRow = {
      rowKey: id,
      id: undefined,
      name: '',
      isMain: '0',
      mobile: '',
      isAdd: true
    };
    const arr = [...dataSource];
    arr.splice(index+1, 0, addRow);
    setDataSource(arr);
    form.setFieldValue(id, addRow);
  }

  const columns = [
    {
      title: '主账号',
      width: 150,
      dataIndex: 'isMain',
      render: (_: any, record: any) => (
        <Item name={[record?.rowKey, 'isMain']} rules={rules} noStyle>
          <Radio.Group options={yesOrNo} />
        </Item>
      )
    },
    {
      title: '电话',
      width: 200,
      dataIndex: 'mobile',
      render: (_: any, record: any) => (
        <Item name={[record?.rowKey, 'mobile']} rules={rules} noStyle>
          <Input />
        </Item>
      )
    },
    {
      title: '姓名',
      width: 150,
      dataIndex: 'name',
      render: (_: any, record: any) => (
        <Item name={[record?.rowKey, 'name']} rules={rules} noStyle>
          <Input />
        </Item>
      )
    },
    {
      title: '操作',
      width: 150,
      dataIndex: 'options',
      render: (_: any, record: any, index: number) => (
        <Space>
          <Button type='link' onClick={() => handleAdd(index)}>新增</Button>
          {index > 0 && <Button type='link' onClick={() => handleDel(record, index)}>删除</Button>}
        </Space>
      )
    },
  ];

  useEffect(() => {
    if (currentRow?.id) {
      fetchPhoneList(currentRow?.id);
    }
  }, [currentRow?.id])
  
  return (
    <Modal
      title={title}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      width="750px"
      maskClosable={false}
    >
      <Form form={form} className="modal-form-padding">
        <Table
          rowKey="rowKey"
          bordered
          columns={columns}
          dataSource={dataSource}
        />
      </Form>
    </Modal>
  );
}

export default CompanyPhoneManage;